<template>
  <div class="signed-agent-detail-product-view">
    <div>
      <el-row>
        <el-col :span="24">
          <div style="display: flex; justify-content: flex-end">
            <el-form :inline="true" class="filter-form-inline" label-position="right" label-width="130px" size="small">
              <el-row :gutter="10">
                <el-col :span="16">
                  <el-form-item label="产品信息" style="width: 100%">
                    <el-select v-model="formData.productId" :loading="loading" :remote-method="remoteMethod" clearable filterable
                               placeholder="请选择产品" remote reserve-keyword
                               @change="listSearch">
                      <el-option v-for="item in products" :key="item.id" :label="item.productPopularName"
                                 :value="item.id"/>
                    </el-select>

                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="">
                    <filter-popover :form-list="formList" right="20px" @onConfirm="filterDataConfirm"
                                    @onReset="filterReset"/>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>

    <el-table :data="tableData" border header-cell-class-name="table-header" size="medium" @row-click="rowClick">
      <el-table-column :min-width="140" align="center" fixed="left" label="编号" prop="agentProductNumber" show-overflow-tooltip
                       type="tags"/>

      <el-table-column :min-width="140" align="left" fixed="left" header-align="center" label="产品通用名"
                       prop="productPopularName" show-overflow-tooltip type="tags"/>

      <el-table-column :min-width="140" align="center" label="商品名" prop="productName" show-overflow-tooltip
                       type="tags"/>

      <el-table-column :min-width="140" align="center" label="包装规格" prop="packSpecs" show-overflow-tooltip
                       type="tags"/>

      <el-table-column :min-width="140" align="center" label="可营销终端" type="tags">
        <template #default="{row}">
          {{ getLabel('app_mode', row.terminalType) }}
        </template>
      </el-table-column>

      <el-table-column :min-width="200" align="center" label="代理地区" show-overflow-tooltip type="tags">
        <template #default="{row}">
          <area-list-view :areas="row.region"/>
        </template>
      </el-table-column>

      <el-table-column label="营销模式" align="center" type="tags">
        <template #default="{row}">
         <span v-if="row.agentType !== 'direct'">
                  {{ row.agentAttribute === '1' ? '区域招商' : '精细招商' }}
                </span>
                <span v-else> 终端直销</span>
        </template>
      </el-table-column>

      <el-table-column :min-width="120" align="center" label="交易价(元)" show-overflow-tooltip type="tags">
        <template #default="{row}">
          <div>{{ row.tradePrice }}</div>
          <div
              v-if="row.flowStatus == 'DOING' && (row.processDefinitionKey == 'agentProductChangePrice' || row.processDefinitionKey == 'agentPersonProductChangePrice')"
              class="flow-status-color">交易价变更审核中
          </div>
        </template>
      </el-table-column>

      <el-table-column :label="type == 'agent' ? '代理期限至' : '兼职期限至'" :min-width="120" align="center" type="tags">
        <template #default="{row}">
          {{ dateFormat('yyyy-mm-dd', row.agentEndTime) }}
        </template>
      </el-table-column>

      <el-table-column :min-width="150" align="center" label="最低销量" show-overflow-tooltip type="tags">
        <template #default="{row}">

          <div v-if="row.minSale">
            {{ row.minSale }}{{
              getLabel('sell_unit', row.sellUnit)
            }}/{{ getLabel('sell_num_unit', row.minSaleUnit + '') }}
          </div>
          <div v-else>未设置</div>
        </template>
      </el-table-column>

      <el-table-column :min-width="150" align="center" label="销量保证金(元)" show-overflow-tooltip type="tags">
        <template #default="{row}">

          <div v-if="row.minSalePromise">
            {{ row.minSalePromise }}
          </div>
          <div v-else>未设置</div>
        </template>
      </el-table-column>

      <el-table-column :min-width="130" align="center" fixed="right" label="负责营销职员" prop="headName" show-overflow-tooltip
                       type="tags"/>

      <el-table-column v-if="datas.tradeStatus == 1" :min-width="120" align="center" fixed="right" label="上月销量"
                       prop="lastMonthSale"
                       show-overflow-tooltip type="tags">
        <template #default="{row}">

          <div class="tab-line">
            <div v-if="row.lastMonthSale">{{ row.lastMonthSale }}</div>
            <div v-else>0</div>
            <div v-if="row.lastMonthSale && row.lastlastMonthSale && (row.lastlastMonthSale != row.lastMonthSale)"
                 :class="dealSellNum(row.lastlastMonthSale,row.lastMonthSale).class">
              {{ dealSellNum(row.lastlastMonthSale, row.lastMonthSale).str }}
            </div>
          </div>

        </template>
      </el-table-column>

      <el-table-column v-if="datas.tradeStatus == 1" :min-width="120" align="center" fixed="right" label="本月销量"
                       prop="thisMonthSale"
                       show-overflow-tooltip type="tags">
        <template #default="{row}">
          <div class="tab-line">
            <div v-if="row.thisMonthSale">{{ row.thisMonthSale }}</div>
            <div v-else>0</div>
            <div v-if="row.lastMonthSale && row.thisMonthSale && (row.thisMonthSale != row.lastMonthSale)"
                 :class="dealSellNum(row.lastMonthSale,row.thisMonthSale).class">
              {{ dealSellNum(row.lastMonthSale, row.thisMonthSale).str }}
            </div>
          </div>

        </template>
      </el-table-column>

      <el-table-column align="center" fixed="right" label="状态" min-width="150px" type="tags">
        <template #default="{row}">
          <span>{{ getStatus(row) }}</span>
        </template>
      </el-table-column>
    </el-table>

    <Pagination :limit="formData.page_size" :page="formData.page_number"
                :total="total" style="display: flex; justify-content: flex-end" @pagination="getListData"/>

    <add-product-dialog ref="addProduct" :agent-id="datas.id" :title="title" :type="type" @success="onSuccess"/>

    <change-product-dialog ref="changeProduct" :agent-id="datas.id" :agent-name="datas.agentName" :type="type"
                           @success="onSuccess"/>

    <invalid-product-dialog ref="invalidProduct" :agent-id="datas.id" :type="type" @success="onSuccess"/>

    <change-price-dialog ref="changePrice" :datas="datas" :type="type" @success="onSuccess"/>

    <register-terminal-dialog ref="registerTerminal" :agent="datas" :agent-product="agentProduct" :type="type"/>

    <detail-drawer ref="detailDrawer" :size-width="1000" custom-title>
      <template #title>
        <div v-if="!isContract" style="display: flex;justify-content: space-between">

          <div>
            <span>代理产品与价格-</span>
            <span class="drawerTitle">{{ agentProduct.agentProductNumber }}</span>
            <el-tag size="small" style="margin-left: 10px" type="warning">
              <template
                  v-if="(agentProduct.processDefinitionKey == 'agentProductCreate' || agentProduct.processDefinitionKey == 'agentPersonProductCreate')
                  && (agentProduct.flowStatus=='DOING' || agentProduct.flowStatus=='REFUSE' || agentProduct.flowStatus=='REPEAL')">
                <span>{{ getLabel('approval_result', agentProduct.flowStatus) }}</span>
              </template>
              <template v-else>{{ getStatus(agentProduct) }}</template>
              <template v-if="agentProduct.flowStatus=='DOING'">
                <span v-if="agentProduct.processDefinitionKey == 'agentProductBan'">[作废审核中]</span>
                <span
                    v-else-if="agentProduct.processDefinitionKey !== 'agentProductCreate' && agentProduct.processDefinitionKey !== 'agentPersonProductCreate'">[{{
                    getLabel('approval_result', agentProduct.flowStatus)
                  }}]</span>
              </template>
            </el-tag>

          </div>

          <div>
            <el-button v-if="agentProduct.agentProductStatus == 1" class="main-btn" size="small" type="primary"
                       @click="changeClick">变更信息
            </el-button>

            <el-button
                v-if="agentProduct.agentProductStatus == 1 && (agentProduct.processDefinitionKey !== 'agentProductBan' || (agentProduct.processDefinitionKey == 'agentProductBan' && agentProduct.flowStatus !=='DOING'))"
                class="main-btn" size="small" type="primary" @click="invalidClick">作废
            </el-button>
          </div>

        </div>

        <div v-else>
          <span>合同 </span>

          <span class="drawerTitle">{{ agentProduct.contractName }}</span>
        </div>

      </template>
      <template #contents>
        <div v-if="!isContract">
          <item-title title="基本信息"/>

          <product-and-price-detail-view :agent-product="agentProduct" :datas="datas" :type="type"
                                         @contract="contractClick" @editPrice="editPrice"/>

          <item-title title="修改记录"/>

          <operation-view :id="agentProduct.id" mode="agent_product"/>
        </div>

        <div v-else>
          <contract-detail ref="salesDetailDrawer" :contract-id="agentProduct.contractId"/>
        </div>

      </template>
    </detail-drawer>

  </div>
</template>

<script>
import {crmStore} from "@CRM/store";
import contractDetail from "@CRM/views/commonView/contract/contractDetail.vue";
import registerTerminalDialog from "./modules/registerTerminalDialog.vue";
import changePriceDialog from "./modules/changePriceDialog.vue";
import invalidProductDialog from "./modules/invalidProductDialog.vue";
import changeProductDialog from "./modules/changeProductDialog.vue";
import productAndPriceDetailView from "./modules/productAndPriceDetailView.vue";
import addProductDialog from "./modules/addProductDialog.vue";
import {useRoute} from "vue-router";
import {defineComponent, getCurrentInstance, inject, onBeforeMount, reactive, ref, toRefs,} from "vue";

export default defineComponent({
  name: "ProductAndPriceView",
  components: {
    addProductDialog,
    productAndPriceDetailView,
    changeProductDialog,
    invalidProductDialog,
    changePriceDialog,
    registerTerminalDialog,
    contractDetail,
  },
  props: {
    datas: {
      type: Object,
      default: {},
    },
    type: {
      type: String,
      default: "agent",
    },
  },
  setup(props, context) {
    const route = useRoute();
    const api = inject("api");
    const currentInstance = getCurrentInstance();
    var detailDrawer = ref(null);
    var addProduct = ref(null);
    var changeProduct = ref(null);
    var invalidProduct = ref(null);
    var changePrice = ref(null);
    var registerTerminal = ref(null);
    var tableData = ref([]);
    var total = ref(0);
    var agentProduct = ref({});
    var title = ref("新增代理产品与价格");
    var isContract = ref(false);
    var contractList = ref([]);
    var headOptions = ref([]);
    var data = reactive({
      formData: {
        page: 1,
        pageSize: 20,
        productId: "",
        agentProductStatus: "",
        agentAttribute: "",
        dateRange: [],
        headId: "",
        contractId: "",
      },
      loading: false,
      products: [],
      contractList: [],
      formList: [
        {
          key: "agentProductStatus",
          label: "状态",
          form_type: "select",
          value: "",
          is_search: false,
          options: [
            {
              value: "-2",
              label: "已作废",
            },
            {
              value: "-1",
              label: "无效",
            },
            {
              value: "1",
              label: "审核中",
            },
            {
              value: "2",
              label: "有效",
            },
          ],
        },
        {
          key: "agentAttribute",
          label: "代理属性",
          form_type: "select",
          value: "",
          is_search: false,
          options: crmStore.getters["dictionary/getDictionary"][props.type],
        },
        {
          key: "dateRange",
          label: "代理期限至",
          form_type: "daterange",
          value: [],
          is_search: false,
          options: [],
        },
        {
          key: "headId",
          label: "营销职员",
          form_type: "select",
          value: "",
          is_search: false,
          options: headOptions,
        },
        {
          key: "contractId",
          label: "关联代理合同",
          form_type: "select",
          value: "",
          is_search: false,
          options: contractList,
        },
      ],
    });

    const dealSellNum = (last, now) => {
      if (last == now || !last || !now) {
        return {};
      }
      let classStr = "";
      let unit = "";
      const num = ((now - last) / last) * 100;

      if (num < 0) {
        classStr = "desc-num";
        unit = "↓";
      } else {
        classStr = "asc-num";
        unit = "↑";
      }
      const str = num.toFixed(2) + "%" + unit;
      return {class: classStr, str: str};
    };

    const remoteMethod = (query) => {
      data.products = [];
      data.loading = true;

      const a = {
        id: props.datas.id,
        productPopularName: "",
      };
      if (query) {
        a.productPopularName = query;
      }

      api.signedAgent.AGENT_PRODUCT_PRODUCT_LIST(a).then((res) => {
        data.loading = false;
        if (!res.code && res.data) {
          res.data.agentProduct.forEach((item) => {
            item.name =
                item.productPopularName + item.packSpecs + item.approvalNumber;
          });
          data.products = res.data.agentProduct;
        }
      });
    };

    const filterDataConfirm = (formdata) => {
      data.formData.page = 1;
      data.formData.agentProductStatus = formdata.agentProductStatus;
      data.formData.agentAttribute = formdata.agentAttribute;
      data.formData.dateRange = formdata.dateRange;
      data.formData.headId = formdata.headId;
      data.formData.contractId = formdata.contractId;
      getListData();
    };

    const listSearch = () => {
      data.formData.page = 1;

      getListData();
    };

    const filterReset = () => {
      data.formData = {
        page: 1,
        pageSize: 20,
        productId: "",
        agentProductStatus: "",
        agentAttribute: "",
        dateRange: [],
        headId: "",
        contractId: "",
      };
      getListData();
    };

    const getListData = (id) => {
      const a = JSON.parse(JSON.stringify(data.formData));
      a.agentId = Number(route.query.id);
      a.productId = Number(a.productId);
      a.headId = Number(a.headId);
      a.contractId = Number(a.contractId);
      if (a.dateRange && a.dateRange.length > 1) {
        a.startTime = a.dateRange[0];
        a.endTime = a.dateRange[1];
      }
      api.signedAgent.AGENT_PRODUCT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          tableData.value = res.data.list;
          total.value = res.data.total;
        }
      });
    };

    const getContract = () => {
      const a = {
        objectId: props.datas.id ? props.datas.id : Number(route.query.id),
        contractObjectType: props.type,
      };
      api.common.VALID_CONTRACT_LIST(a).then((res) => {
        if (!res.code && res.data) {
          res.data.list.forEach((item) => {
            item.value = item.id;
            item.label = item.contractName;
          });
          contractList.value = res.data.list;
        }
      });
    };

    // 获取负责人
    const handlHead = () => {
      api.terminal.HEAD_PEOPLE(1).then((res) => {
        if (res.code === 0) {
          res.data.forEach((item) => {
            item.value = item.id;
            item.label = item.realName;
          });
          headOptions.value = res.data;
        }
      });
    };

    onBeforeMount(() => {
      if (route.query.id) {
        getListData(route.query.id);
      }
      getContract();
      handlHead();
    });

    const addClick = () => {
      title.value = "新增代理产品与价格";
      addProduct.value.openDialog();
    };

    const onSuccess = () => {
      getListData(props.datas.id);

      if (agentProduct.value.id) {
        api.signedAgent
            .AGENT_PRODUCT_DETAIL(agentProduct.value.id)
            .then((res) => {
              if (!res.code && res.data) {
                agentProduct.value = res.data.agentProduct;
              }
            });
      }
    };

    const getStatus = (row) => {
      let str = "";
      switch (row.agentProductStatus) {
        case "-2":
          str = "已作废";
          break;
        case "-1":
          str = "未通过";
          break;
        case "1":
          str = "审核中";
          break;
        case "2":
          str = "有效";
          break;
      }
      return str;
    };

    const rowClick = (row) => {
      isContract.value = false;
      api.signedAgent.AGENT_PRODUCT_DETAIL(row.id).then((res) => {
        if (!res.code && res.data) {
          agentProduct.value = res.data.agentProduct;

          detailDrawer.value.open();
        }
      });
    };

    const contractClick = () => {
      isContract.value = true;
    };

    const changeClick = () => {
      const a = JSON.parse(JSON.stringify(agentProduct.value));
      changeProduct.value.openDialog(a);
    };

    const invalidClick = () => {
      api.signedAgent
          .AGENT_PRODUCT_BANJUDGE(agentProduct.value.id)
          .then((res) => {
            if (!res.code && res.data) {
              if (res.data.inUse == 1) {
                currentInstance.proxy.customMessage({
                  type: "error",
                  message: "该代理与产品有关联的交易信息，暂时无法作废",
                });
              } else {
                const a = JSON.parse(JSON.stringify(agentProduct.value));
                invalidProduct.value.openDialog(a);
              }
            }
          });
    };

    const editPrice = () => {
      const a = JSON.parse(JSON.stringify(agentProduct.value));
      changePrice.value.openDialog(a);
    };

    const onRegister = (row) => {
      api.signedAgent.AGENT_PRODUCT_DETAIL(row.id).then((res) => {
        if (!res.code && res.data) {
          agentProduct.value = res.data.agentProduct;

          registerTerminal.value.openDialog(agentProduct.value);
        }
      });
    };

    const onEdit = (row) => {
      title.value = "编辑代理产品与价格";
      addProduct.value.openDialog(row);
    };

    const onDelete = (row) => {
      currentInstance.proxy
          .alertBox({
            message: "是否确认删除该代理产品？",
            title: "删除",
          })
          .then(() => {
            api.signedAgent.AGENT_PRODUCT_DELETE(row.id).then((res) => {
              if (res.code) {
                // currentInstance.proxy.customMessage({type:'error',message:res.msg})
              } else {
                currentInstance.proxy.customMessage({
                  type: "success",
                  message: "删除成功",
                });
                getListData(route.query.id);
              }
            });
          })
          .catch((err) => {
            console.log(err);
          });
    };

    return {
      ...toRefs(data),
      addProduct,
      changeProduct,
      tableData,
      total,
      detailDrawer,
      agentProduct,
      invalidProduct,
      changePrice,
      registerTerminal,
      title,
      isContract,

      addClick,
      getListData,
      onSuccess,
      getStatus,
      rowClick,
      changeClick,
      invalidClick,
      editPrice,
      onRegister,
      onEdit,
      onDelete,
      contractClick,
      remoteMethod,
      filterDataConfirm,
      filterReset,
      listSearch,
      dealSellNum,
    };
  },
});
</script>

<style lang="scss" scoped>
@import "@/style/basics.scss";

.signed-agent-detail-product-view {
  .drawerTitle {
    font-size: 18px;
  }

  .desc-num {
    color: chartreuse;
  }

  .asc-num {
    color: $delete-color;
  }
}
</style>
